import torch
import torch.nn as nn
import torch.optim as optim
from torch.utils.data import DataLoader
from torchvision import datasets, transforms

# 1. 数据预处理与加载
transform = transforms.Compose([
    transforms.ToTensor(),  # 转为张量并归一化到[0,1]
    transforms.Normalize((0.1307,), (0.3081,))  # MNIST数据集的均值和标准差
])

# 加载训练集和测试集
train_dataset = datasets.MNIST(
    root='./data', train=True, download=True, transform=transform
)
test_dataset = datasets.MNIST(
    root='./data', train=False, download=True, transform=transform
)

# 数据加载器（批量读取数据）
train_loader = DataLoader(train_dataset, batch_size=64, shuffle=True)
test_loader = DataLoader(test_dataset, batch_size=1000, shuffle=False)


# 2. 定义CNN模型
class SimpleCNN(nn.Module):
    def __init__(self):
        super(SimpleCNN, self).__init__()
        self.conv1 = nn.Conv2d(1, 32, kernel_size=3, stride=1, padding=1)
        self.relu = nn.ReLU()
        self.pool = nn.MaxPool2d(kernel_size=2, stride=2)
        self.conv2 = nn.Conv2d(32, 64, kernel_size=3, stride=1, padding=1)
        self.fc1 = nn.Linear(64 * 7 * 7, 128)  # 池化后尺寸：28→14→7
        self.fc2 = nn.Linear(128, 10)  # 10个分类（0-9）

    def forward(self, x):
        x = self.pool(self.relu(self.conv1(x)))
        x = self.pool(self.relu(self.conv2(x)))
        x = x.view(-1, 64 * 7 * 7)  # 展平为一维向量
        x = self.relu(self.fc1(x))
        x = self.fc2(x)
        return x


# 3. 初始化组件
model = SimpleCNN()
criterion = nn.CrossEntropyLoss()  # 分类任务损失函数
optimizer = optim.Adam(model.parameters(), lr=0.001)


# 4. 训练函数
def train(model, train_loader, criterion, optimizer, epoch):
    model.train()  # 训练模式
    for batch_idx, (data, target) in enumerate(train_loader):
        optimizer.zero_grad()  # 清空梯度
        output = model(data)   # 前向传播
        loss = criterion(output, target)  # 计算损失
        loss.backward()        # 反向传播
        optimizer.step()       # 更新参数

        # 打印训练进度
        if batch_idx % 100 == 0:
            print(f'Train Epoch: {epoch} [{batch_idx * len(data)}/{len(train_loader.dataset)} '
                  f'({100. * batch_idx / len(train_loader):.0f}%)]\tLoss: {loss.item():.6f}')


# 5. 测试函数
def test(model, test_loader, criterion):
    model.eval()  # 评估模式
    test_loss = 0
    correct = 0
    with torch.no_grad():  # 禁用梯度计算（节省资源）
        for data, target in test_loader:
            output = model(data)
            test_loss += criterion(output, target).item()  # 累计损失
            pred = output.argmax(dim=1, keepdim=True)  # 预测类别
            correct += pred.eq(target.view_as(pred)).sum().item()  # 统计正确数

    test_loss /= len(test_loader.dataset)
    print(f'\nTest set: Average loss: {test_loss:.4f}, '
          f'Accuracy: {correct}/{len(test_loader.dataset)} '
          f'({100. * correct / len(test_loader.dataset):.2f}%)\n')


# 6. 执行训练与测试（训练5轮）
for epoch in range(1, 6):
    train(model, train_loader, criterion, optimizer, epoch)
    test(model, test_loader, criterion)